#pragma once
#include <stdio.h>
#include <stdlib.h>
#include "ColorSpaceConverter.h"


namespace PEL {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;
    using namespace System::Runtime::InteropServices;

	/// <summary>
	/// Summary for Form1
	///
	/// WARNING: If you change the name of this class, you will need to change the
	///          'Resource File Name' property for the managed resource compiler tool
	///          associated with all .resx files this class depends on.  Otherwise,
	///          the designers will not be able to interact properly with localized
	///          resources associated with this form.
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
            colorSpace = NULL;


			//
			//TODO: Add the constructor code here
			//
		}

	protected:
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}
    private: System::Windows::Forms::PictureBox^  display;
    private: System::Windows::Forms::Button^  play;
    private: System::Windows::Forms::Button^  Pause;
    private: System::Windows::Forms::Button^  open;





    protected: 

    protected: 

	private:
		/// <summary>
        String^ fileName;
        FILE*  videoFile;

        ColorSpaceConverter* colorSpace;


    private: System::Windows::Forms::TextBox^  width;
    private: System::Windows::Forms::TextBox^  height;






		/// </summary>
		System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		void InitializeComponent(void)
		{
        System::ComponentModel::ComponentResourceManager^  resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid));
        this->display = (gcnew System::Windows::Forms::PictureBox());
        this->play = (gcnew System::Windows::Forms::Button());
        this->Pause = (gcnew System::Windows::Forms::Button());
        this->open = (gcnew System::Windows::Forms::Button());
        this->width = (gcnew System::Windows::Forms::TextBox());
        this->height = (gcnew System::Windows::Forms::TextBox());
        (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->display))->BeginInit();
        this->SuspendLayout();
        // 
        // display
        // 
        this->display->Anchor = System::Windows::Forms::AnchorStyles::None;
        this->display->Location = System::Drawing::Point(12, 16);
        this->display->Name = L"display";
        this->display->Size = System::Drawing::Size(352, 288);
        this->display->SizeMode = System::Windows::Forms::PictureBoxSizeMode::CenterImage;
        this->display->TabIndex = 0;
        this->display->TabStop = false;
        // 
        // play
        // 
        this->play->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Left));
        this->play->BackColor = System::Drawing::Color::DimGray;
        this->play->FlatAppearance->BorderColor = System::Drawing::Color::DimGray;
        this->play->FlatAppearance->BorderSize = 0;
        this->play->FlatAppearance->MouseDownBackColor = System::Drawing::Color::LightGray;
        this->play->FlatAppearance->MouseOverBackColor = System::Drawing::Color::DarkGray;
        this->play->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
        this->play->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
            static_cast<System::Byte>(0)));
        this->play->ForeColor = System::Drawing::SystemColors::InactiveCaption;
        this->play->Location = System::Drawing::Point(148, 319);
        this->play->Name = L"play";
        this->play->Size = System::Drawing::Size(57, 23);
        this->play->TabIndex = 1;
        this->play->Text = L"Play";
        this->play->UseVisualStyleBackColor = false;
        this->play->Click += gcnew System::EventHandler(this, &Form1::play_Click);
        // 
        // Pause
        // 
        this->Pause->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Left));
        this->Pause->BackColor = System::Drawing::Color::DimGray;
        this->Pause->FlatAppearance->BorderColor = System::Drawing::Color::DimGray;
        this->Pause->FlatAppearance->BorderSize = 0;
        this->Pause->FlatAppearance->MouseDownBackColor = System::Drawing::Color::LightGray;
        this->Pause->FlatAppearance->MouseOverBackColor = System::Drawing::Color::DarkGray;
        this->Pause->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
        this->Pause->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
            static_cast<System::Byte>(0)));
        this->Pause->ForeColor = System::Drawing::SystemColors::InactiveCaption;
        this->Pause->Location = System::Drawing::Point(211, 319);
        this->Pause->Name = L"Pause";
        this->Pause->Size = System::Drawing::Size(57, 23);
        this->Pause->TabIndex = 3;
        this->Pause->Text = L"Pause";
        this->Pause->UseVisualStyleBackColor = false;
        // 
        // open
        // 
        this->open->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Left));
        this->open->BackColor = System::Drawing::Color::DimGray;
        this->open->FlatAppearance->BorderColor = System::Drawing::Color::DimGray;
        this->open->FlatAppearance->BorderSize = 0;
        this->open->FlatAppearance->MouseDownBackColor = System::Drawing::Color::LightGray;
        this->open->FlatAppearance->MouseOverBackColor = System::Drawing::Color::DarkGray;
        this->open->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
        this->open->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
            static_cast<System::Byte>(0)));
        this->open->ForeColor = System::Drawing::SystemColors::InactiveCaption;
        this->open->Location = System::Drawing::Point(85, 319);
        this->open->Name = L"open";
        this->open->Size = System::Drawing::Size(57, 23);
        this->open->TabIndex = 4;
        this->open->Text = L"Open";
        this->open->UseVisualStyleBackColor = false;
        this->open->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
        // 
        // width
        // 
        this->width->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Left));
        this->width->Location = System::Drawing::Point(12, 319);
        this->width->Name = L"width";
        this->width->Size = System::Drawing::Size(53, 20);
        this->width->TabIndex = 5;
        this->width->Text = L"352";
        // 
        // height
        // 
        this->height->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Left));
        this->height->Location = System::Drawing::Point(12, 345);
        this->height->Name = L"height";
        this->height->Size = System::Drawing::Size(53, 20);
        this->height->TabIndex = 6;
        this->height->Text = L"288";
        // 
        // Form1
        // 
        this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
        this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
        this->BackColor = System::Drawing::Color::Black;
        this->ClientSize = System::Drawing::Size(380, 389);
        this->Controls->Add(this->height);
        this->Controls->Add(this->width);
        this->Controls->Add(this->open);
        this->Controls->Add(this->Pause);
        this->Controls->Add(this->play);
        this->Controls->Add(this->display);
        this->Icon = (cli::safe_cast<System::Drawing::Icon^  >(resources->GetObject(L"$this.Icon")));
        this->Name = L"Form1";
        this->Text = L"PEL Player";
        this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
        (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->display))->EndInit();
        this->ResumeLayout(false);
        this->PerformLayout();

            }
#pragma endregion
    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
             }
    private: System::Void play_Click(System::Object^  sender, System::EventArgs^  e) {


                 char* filenameChar = (char*) Marshal::StringToHGlobalAnsi(fileName).ToPointer();

                 FILE* fp = fopen(filenameChar, "r+b");

                 if (fp == NULL) {
                     System::Windows::Forms::MessageBox::Show(L"ERROR!!! File dosent Exsist!!!",
                                      L"File Not Found",
                                      MessageBoxButtons::OK,
                                      MessageBoxIcon::Error,
                                      MessageBoxDefaultButton::Button1,
                                      MessageBoxOptions::RightAlign,
                                      false);
                     return;
                 }

                 int frameWidth  = atoi((char*) Marshal::StringToHGlobalAnsi(this->width->Text).ToPointer());
                 int frameHeight = atoi((char*) Marshal::StringToHGlobalAnsi(this->height->Text).ToPointer());
                 int frameLength = frameWidth * frameHeight * 1.5;

                 if (colorSpace == NULL) {
                     colorSpace = new ColorSpaceConverter(frameWidth, frameHeight);
                 }

                 updateControlPosition(frameWidth, frameHeight);

                 unsigned char* filebuffer = new unsigned char[frameLength];
                 unsigned char* destBuffer = new unsigned char[frameLength * 2];

                 fread(filebuffer, 1, frameLength, fp);

                 colorSpace->Convert420ToRGB(filebuffer, destBuffer);

                 //char *thpPtr = destBuffer;
                 //for (int i = 0; i < frameWidth * frameHeight; i++) {
                 //    *thpPtr++     = filebuffer[i];
                 //    *thpPtr++ = filebuffer[i];
                 //    *thpPtr++ = filebuffer[i];
                 //}

                 Bitmap^ theImage = gcnew Bitmap(frameWidth, frameHeight, frameWidth * 3, 
                                                 System::Drawing::Imaging::PixelFormat::Format24bppRgb,
                                                 System::IntPtr((void*) destBuffer));

                 display->Image = dynamic_cast<Image^>(theImage);

                 if (colorSpace != NULL) {
                     delete colorSpace;
                     colorSpace = NULL;
                 }

                 //if (NULL != destBuffer) {
                 //    delete [] destBuffer;
                 //    destBuffer = NULL;
                 //}
                 //if (NULL != filebuffer) {
                 //    delete [] filebuffer;
                 //    filebuffer = NULL;
                 //}
             }


private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

            OpenFileDialog^ theDialog = gcnew OpenFileDialog();

            theDialog->Filter = "Luma Image files (*.y)|*.y|yuv files (*.yuv)|*.yuv";
            theDialog->InitialDirectory = "c:\\";
            theDialog->FilterIndex = 2;
            theDialog->RestoreDirectory = false;

            fileName = nullptr;

            if ( theDialog->ShowDialog() == System::Windows::Forms::DialogResult::OK ) {
                if ( theDialog->FileName != nullptr ) {
                    fileName = theDialog->FileName;
                }
            }

            this->play_Click(sender, e);
}

 private: void updateControlPosition (int frameWidth, int frameHeight) {

                this->ClientSize = System::Drawing::Size(frameWidth + 30, frameHeight + 50);
                this->display->Size = System::Drawing::Size(frameWidth, frameHeight);

            }
};
}

